package com.xz.simplerpc.rpc.invokers;

import com.xz.simplerpc.rpc.api.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Random;

/**
 * Created by fingal on 2018/1/13.
 */
public class FailoverClusterInvoker<T> implements Invoker<T> {

    private static final Logger logger = LoggerFactory.getLogger(FailoverClusterInvoker.class);

    protected final Directory<T> directory;

    public FailoverClusterInvoker(Directory<T> directory) {
        this.directory = directory;
    }

    @Override
    public Class<T> getInterface() {
        return null;
    }

    @Override
    public Result invoke(Invocation invocation) throws RpcException {
        List<Invoker<T>> invokers = list(invocation);

        if (logger.isDebugEnabled()) {
            logger.debug("providers list size: " + invokers.size());
        }

        //do select with loadbalance
        //在此例中，用最简单的随机选择，替换负载策略
        Random random = new Random();

        Invoker<T> invoker = null;
        if(invokers.size() == 1) {
            invoker = invokers.get(0);
        } else {
            invoker = invokers.get(random.nextInt(invokers.size()));
        }

        return invoker.invoke(invocation);
    }

    private List<Invoker<T>> list(Invocation invocation) {
        return directory.list(invocation);
    }

    public static void main(String[] args) {
        Random random = new Random();
        for (int i=0; i<= 10; i++) {
            System.out.println(random.nextInt(2));
        }

    }
}
